package com.situ.blog.interceptor;


import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.situ.blog.pojo.entity.User;

import java.util.Map;

public class LoginInterceptor implements Interceptor {

    public LoginInterceptor() {
        System.out.println("LoginInterceptor MyInterceptor1()");
    }

    @Override
    public void init() {
        System.out.println("LoginInterceptor init()");
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("LoginInterceptor intercept() 开始");

        //如果已经登录，放行（访问下一个拦截器或者是Action）
        //如果没有登录：转发到登录界面
        //特殊情况处理：拿到当前执行的方法名：判断只有当前方法名不是login才去验证

        //获得ActionContext对象
        ActionContext actionContext = invocation.getInvocationContext();
        //获得Action代理类
        ActionProxy proxy = invocation.getProxy();
        //获得当前执行的方法名
        String methodName = proxy.getMethod();
        //特殊情况判断
        if (!"login".equalsIgnoreCase(methodName) && !"checkImage".equalsIgnoreCase(methodName)) {
            Map<String, Object> sessionMap = actionContext.getSession();
            User user = (User) sessionMap.get("user");
            if (user == null) {
                return Action.LOGIN;
            }
        }
        //访问下一个拦截器或者Action
        return invocation.invoke();

    }

    @Override
    public void destroy() {
        System.out.println("LoginInterceptor destroy()");

    }
}
